import { useEffect, useRef, useState } from "react";

interface ILayout {
  text: string;
  side: string;
  height: number;
}

export const usePoster = () => {
  // 用于引用名字元素，以便获取其高度
  const nameRef = useRef<HTMLDivElement>(null);

  // 生成5个随机高度，总和为30vh，都是整数，避免过大或过小
  const generateRandomHeights = () => {
    const heights = [];
    let remaining = 30;

    // 生成前4个高度，确保每个都在合理范围内（4-8vh）
    for (let i = 0; i < 4; i++) {
      // 最小高度4，最大高度8，但要考虑剩余空间
      const minHeight = Math.max(4, remaining - (4 - i) * 8);
      const maxHeight = Math.min(8, remaining - (4 - i) * 4);
      const height =
        Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight;
      heights.push(height);
      remaining -= height;
    }

    // 最后一个高度就是剩余的高度
    heights.push(remaining);

    return heights;
  };

  // 生成交替布局配置
  const generateAlternatingLayout = () => {
    const texts = ["展", "程", "的", "基", "地"];
    const heights = generateRandomHeights();

    // 随机决定第一个文字在左边还是右边
    const firstSide = Math.random() < 0.5 ? "left" : "right";

    const layout = [];
    for (let i = 0; i < texts.length; i++) {
      const side =
        i % 2 === 0 ? firstSide : firstSide === "left" ? "right" : "left";
      layout.push({
        text: texts[i],
        side: side,
        height: heights[i],
      });
    }

    return layout;
  };

  const [layout, setLayout] = useState<ILayout[]>([]);
  const maxHeight = Math.max(...layout.map((item) => item.height));

  const calculateLineHeight = () => {
    const viewportHeight = window.innerHeight;

    if (nameRef.current) {
      const nameHeight = nameRef.current.offsetHeight;
      // 计算线条高度：(屏幕高度 - 名字高度) / 2
      const calculatedLineHeight = (viewportHeight - nameHeight) / 2;
      document.documentElement.style.setProperty(
        "--dynamic-line-height",
        `${calculatedLineHeight}px`
      );
    }
  };

  useEffect(() => {
    calculateLineHeight();
    setLayout(generateAlternatingLayout());
  }, []);

  return {
    nameRef,
    layout,
    maxHeight,
  };
};
